package com.task.controller;

import com.task.bean.Constants;
import com.task.bean.JsTokenBean;
import com.task.service.IWxService;
import com.task.utils.PropertiesUtil;
import com.task.utils.RenderUtil;
import com.task.weixin.WXBizMsgCrypt;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * 微信验证token
 * Created by wangmin on 15-10-22.
 */
@Controller
public class WechatController {

    private String TOKEN = "845C2550903CE6FA54CACDB82EAD4350";

    private static final Logger LOGGER = LoggerFactory.getLogger(WechatController.class);

    static Charset CHARSET = Charset.forName("utf-8");

    @Autowired
    IWxService wxService;

    @RequestMapping(value = "/wechat")
    public void verifyToken(@RequestParam(value = "signature", defaultValue = "") String signature,
                            @RequestParam(value = "echostr", defaultValue = "") String echostr,
                            @RequestParam(value = "timestamp", defaultValue = "") String timestamp,
                            @RequestParam(value = "nonce", defaultValue = "") String nonce,
                            HttpServletResponse response) {

        try {
            if (StringUtils.isNotBlank(signature) && StringUtils.isNotBlank(nonce)
                    && StringUtils.isNotBlank(timestamp) &&
                    StringUtils.isNotBlank(echostr)) {

                String[] str = {TOKEN, timestamp, nonce};
                Arrays.sort(str); // 字典序排序
                String bigStr = str[0] + str[1] + str[2];

                // SHA1加密
                MessageDigest md = MessageDigest.getInstance("SHA-1");
                md.update(bigStr.getBytes("UTF-8"));
                byte[] result = md.digest();
                StringBuffer sb = new StringBuffer();

                for (byte b : result) {
                    int i = b & 0xff;
                    if (i < 0xf) {
                        sb.append(0);
                    }
                    sb.append(Integer.toHexString(i));
                }

                // 确认请求来至微信
                if (StringUtils.equals(sb.toString(), signature)) {
                    response.getWriter().print(echostr);
                } else {
                    response.getWriter().print("error");
                }
            }
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("verifyToken fail : {}", e);
        } catch (IOException e) {
            LOGGER.error("verifyToken fail : {}", e);
        }
    }

/*    *//**
     * 企业公众号通知登录
     *
     * @param msg_signature
     * @param timestamp
     * @param nonce
     * @param response
     *//*
    @RequestMapping(value = "/verifyCorp",method = RequestMethod.POST)
    public void noticeCorp(@RequestParam(value = "msg_signature", defaultValue = "") String msg_signature,
                           @RequestParam(value = "timestamp", defaultValue = "") String timestamp,
                           @RequestParam(value = "nonce", defaultValue = "") String nonce,
                           HttpServletRequest request,
                           HttpServletResponse response) {
        try {
            LOGGER.info("msg_signature:{},timestamp:{},nonce:{}", msg_signature,timestamp, nonce);
            if (StringUtils.isNotBlank(msg_signature) && StringUtils.isNotBlank(nonce)
                    && StringUtils.isNotBlank(timestamp)) {

                //################ 从请求中读取整个post数据 ################
                InputStream inputStream = request.getInputStream();

                //################ commons.io.jar方法 ################
                String post = IOUtils.toString(inputStream, "UTF-8");
                LOGGER.info(String.format("Post打印结果:[%s]", post));

                WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(PropertiesUtil.getProperty("token"), PropertiesUtil.getProperty("encodingAESKey"), PropertiesUtil.getProperty("corpID"));
                String Msg = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, post);
                LOGGER.info("Msg打印结果:{}", Msg);
                RenderUtil.renderText(Msg,response);
            }
        } catch (Exception e) {
            LOGGER.error("noticeCorp fail : {}", e);
        }
    }*/

    /**
     * 企业公众号验证
     *
     * @param msg_signature
     * @param echostr
     * @param timestamp
     * @param nonce
     * @param response
     */
    @RequestMapping(value = "/verifyCorp", method = RequestMethod.GET)
    public void verifyCorp(@RequestParam(value = "msg_signature", defaultValue = "") String msg_signature,
                           @RequestParam(value = "echostr", defaultValue = "") String echostr,
                           @RequestParam(value = "timestamp", defaultValue = "") String timestamp,
                           @RequestParam(value = "nonce", defaultValue = "") String nonce,
                           HttpServletResponse response) {
        try {
            LOGGER.info("msg_signature:{},echostr:{},timestamp:{},nonce:{}", msg_signature, echostr, timestamp, nonce);
            if (StringUtils.isNotBlank(msg_signature) && StringUtils.isNotBlank(nonce)
                    && StringUtils.isNotBlank(timestamp) &&
                    StringUtils.isNotBlank(echostr)) {

                WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(PropertiesUtil.getProperty(Constants.TOKEN), PropertiesUtil.getProperty(Constants.ENCODING_AES_KEY), PropertiesUtil.getProperty(Constants.CORPID));
                String result = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr);

                // 确认请求来至微信
                LOGGER.info("result:{}", result);
                RenderUtil.renderText(result, response);
            }
        } catch (Exception e) {
            LOGGER.error("verifyCorp fail : {}", e);
        }
    }

    /**
     * 微信应用配置地址
     * @param code
     * @param response
     * @return
     */
    @RequestMapping(value = "/mobileIndex.html")
    public String callBack(@RequestParam(value = "code", defaultValue = "") String code,
                           HttpServletResponse response) {
        try {
            LOGGER.info("getWeiXinUserInfo.json，code：{}", code);
            if (StringUtils.isNotBlank(code)) {//未初始化
                String userId = wxService.saveWxUserInfo(code);
                if (StringUtils.isNotBlank(userId)) {
                    return "redirect:/mobile.html?userId=" + userId;
                }
            }
        } catch (Exception e) {
            LOGGER.error("callBack.json error:{}", e);
        }
        return "mobile/phone_error";
    }

    @ResponseBody
    @RequestMapping(value = "/getJsApiConfigParams.json")
    public JsTokenBean getJsApiConfigParams(@RequestParam(value = "url", defaultValue = "") String url) {
        JsTokenBean jsTokenBean = new JsTokenBean();
        try {
            jsTokenBean = wxService.saveAndGetAuthorityInfo(url);
        } catch (Exception e) {
            LOGGER.error("getJsApiConfigParams : {}", e);
        }
        return jsTokenBean;
    }


    @RequestMapping(value = "/webWxTest")
    public String webWxTest() {
        return "/mobile/test";
    }
}
